const { LoadPolicy } = require("@/utils/casbin");
const { sendData } = require("@/utils/r/result");
const { ErrorCode } = require("@/utils/r/code");

function RBAC() {
  const Load_Policy = async () => await LoadPolicy();
  return async (req, res, next) => {
    await Load_Policy();
    const role = req["role"];
    let url = req.path.replace(/\/api/, "");
    const method = req.method;
    url = url.replace(/\/\d+/, "/:id"); //如果当前路径存在数字，则代码是路径参数params
    const isPass = await global.e.enforce(role, url, method);

    if (url === "/login") {
      next();
      return;
    }
    if (isPass) {
      //鉴权通过
      next();
    } else {
      sendData(res, ErrorCode.ERROR_PERMI_DENIED);
      return;
    }
  };
}

module.exports = RBAC;
